/*
 * @Author: i@douxuefeng.cn
 * @Date: 2021-12-22 15:15:00
 * @LastEditTime: 2021-12-23 13:58:18
 * @LastEditors: i@douxuefeng.cn
 * @Description:
 * @FilePath: \go-im\ws\ws_conn.go
 */
package ws

import (
	"encoding/json"
	"net/http"
	"strconv"
	"time"

	"gitee.com/douxuefeng/go-im/params"
	"gitee.com/douxuefeng/go-utils/request"
	"gitee.com/douxuefeng/go-utils/strs"
	gorillaws "github.com/gorilla/websocket"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/websocket"
	"github.com/kataras/neffos"
	"github.com/kataras/neffos/gorilla"
)

var upgrader = gorilla.Upgrader(gorillaws.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
})

var event = neffos.Events{
	neffos.OnNativeMessage: func(n *neffos.NSConn, m neffos.Message) error {
		if !n.Conn.IsClient() {
			uid, err := strconv.ParseInt(n.Conn.ID(), 10, 64)
			if err != nil {
				n.Conn.Close()
			}
			var msg params.ReceiveMsg
			err = json.Unmarshal(m.Body, &msg)
			if err != nil {
				return err
			}
			NewHandler(handlerParams{
				uid:  uid,
				msg:  msg,
				conn: n,
				ctx:  websocket.GetContext(n.Conn),
			}).Deal()
		}
		return nil
	},
}
var IdGenerator = func(ctx iris.Context) string {
	return ctx.URLParam("token")
}

func WebsocketServer() *neffos.Server {
	ws := neffos.New(upgrader, event)
	ws.OnConnect = func(c *neffos.Conn) error {
		uid, err := strconv.ParseInt(c.ID(), 10, 64)
		if err != nil {
			c.Close()
		}
		if _, ok := params.UserTokens.Load(uid); !ok {
			// // 获取用户信息并保存在
			req := request.NewRequest()
			// 校验 用户权限
			res := req.Get("url")
			var result params.Result
			err := json.Unmarshal(res.Body(), &result)
			if err != nil || result.Code != 200 {
				body, _ := json.Marshal(iris.Map{
					"code": 401,
					"msg":  "用户信息不存在，请登录",
				})
				c.Write(neffos.Message{
					IsNative: true,
					Body:     body,
				})
				c.Close()
			} else {
				params.UserTokens.Store(uid, result.Data)
			}
		}
		return nil
	}
	ws.OnDisconnect = func(c *neffos.Conn) {
		c.Close()
	}
	return ws
}
